<?php

class Setting
{
    public static function getVar($name, $value = '')
    {
        $db = Registry::get('db');
        $sql = sprintf('select value, limittime, created from settings where name = "%s"', $name);
        $result = $db->Query($sql);
        $set = $result[0]['value'];
        if (!$set) {
            return false;
        } else {
            $re = unserialize($set);
        }
        if ( $result[0]['limittime'] > 0 and time() - $result[0]['created'] > $result[0]['limittime']) {
            self::deleteVar($name);
            return false;
        }
        return $re;
    }
    
    /**
     * set the variable value by name
     *
     * @param string $name
     * @param string $value
     * @return bool
     */
    public static function setVar($name, $value, $flag = '0', $time = '0')
    {
        $db = Registry::get('db');
        $sql = sprintf('select value from settings where name = "%s"', $name);
        $result = $db->Query($sql);
        $set = $result[0]['value'];
        $value = serialize($value);
        if (!$set) {
            $sql = sprintf('insert into settings (name, value, flag, limittime, created) values ("%s", \'%s\', %d, %d, %d)', $name, addslashes($value), $flag, $time, time());
            $result = $db->Execute($sql);
        } else {
            $sql = sprintf('update settings set value = "%s", limittime = %d, flag = %d, created = %d where name = "%s"', addslashes($value),  $time, $flag, time(), $name);
            $result = $db->Execute($sql);
        }
        return $result;
    }
    
    /**
     * delete value by name
     *
     * @param string $name
     * @return bool
     */
    public static function deleteVar($name)
    {
        $db = Registry::get('db');
        $sql = sprintf('delete from settings where name = "%s"', $name);
        $result = $db->Execute($sql);
        return $result;
    }
}
